import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { connect } from 'dva';
import moment from 'moment';
import { Modal,message, Button,} from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import styles from '@/components/common/PateoTable/TableList.less';
import { getMd5, getKeyValueString, getToken } from '@/utils/utils';
import { getDictOptionsByCode } from '@/support/common';
import PropTypes from 'prop-types';
import { fingerprintFetch } from '@/utils/request'

const mapStateToProps = (state: any) => ({
  dataCollectionTaskCenter: state.dataCollectionTaskCenter,
  loading: state.loading.models["dataCollectionTaskCenter"],
});

class TaskCenter extends PureComponent<any, any> {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, dispatch } = this.props
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      //  打开弹窗
      const { formValues } = this.state;
      const tempParam = {
        ...formValues,
        page: 1,
        size: 10
      }
      dispatch({
        type: 'dataCollectionTaskCenter/getFetchPage',
        payload: { url: '/remote/config/taskCenter/page', functionType: 'collectionConfig', ...tempParam},
        callback: (res: any) => {
          console.log(res)
        }
      })
    }
  }

  //  重置
  handleFormReset = () => {
    this.setState({
      formValues: {}
    });
  }

  close = () => {
    const { closeModal } = this.props;
    closeModal();
  };


  // handleDownloadLog = (record: any) => {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: 'http/postObjWithRes',
  //     payload: {
  //       url: '/remote/config/taskCenter/reExecute',
  //       taskId: record.sid,
  //     },
  //     callback: (res: any) => {
  //       if (res.statusCode === '0') {
  //         message.success('操作成功')
  //         this.handleFresh()
  //       }
  //     }
  //   })
  // }

  handleFresh = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      pageNo: 1,
      pageSize: 10
    }
    dispatch({
      type: 'dataCollectionTaskCenter/getFetchPage',
      payload: { url: '/remote/config/taskCenter/page', functionType: 'collectionConfig', ...tempParam},
    });
  }
  downloadFileByUrl = (url:any, name:any) => {
    let str = `${window.g.url}/common/getfile/byurl`;
    let obj = { url };
    const obj1 = Object.assign({}, obj);
    let dataStr = getKeyValueString(obj1)
    let md5 = getMd5(dataStr)
    const newOptions = {};
    newOptions.method = 'POST';
    newOptions.body =  dataStr;
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      OptAuthorization: `${getToken()}`,
        shaSign: md5,
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(e => {
        message.error('下载失败，请稍后在试!');
      });
  };
   handleDownloadLog = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/remote/config/taskCenter/reExecute',
        taskId: record.sid,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('操作成功')
          this.handleFresh()
        }
      }
    })
  }


  render() {
    const { modalVisible } = this.props
    const { dataCollectionTaskCenter: { pageData: { list, pagination }, }, loading } = this.props;
    const { formValues, } = this.state
    const optOptions =  getDictOptionsByCode(this.context.dicData, 'exportFieldType');

    const searchItems = [
      {
        title: '操作类型',
        type: 'select',
        selectOptions: optOptions,
        key: 'operationType',
      },
    ]

    const columns = [
      {
        title: '操作类型',
        dataIndex: 'operationName',
      },
      {
        title: '操作时间',
        dataIndex: 'createDate',
        render: (text: any, record: any) => {
          return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ''
        }
      },
      {
        title: '操作人',
        dataIndex: 'createBy',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: (text: any, record: any) => {
          return text == 0 ? '失败' : text == 1 ? '进行中' : text == 2 ? '成功' : '';
        }
      },
      {
        title: '操作区',
        dataIndex: 'url',
        fixed: 'right',
        render: (text: any, record: any) => {
          if (text) {
            // let findText = enums.platformThirdType.array.find(
            //   (e) => e.value === record.type
            // );
            return (
              <a
                onClick={() => {
                  this.downloadFileByUrl(
                    text,
                    '导出字段' +
                      moment(record.createDate).format("YYYY-MM-DD HH:mm:ss") +
                      ".xlsx"
                  );
                }}
              >
                文件下载
              </a>
            );
          }else{
            return ''
            //需求修改，暂时屏蔽重新执行功能
            // if(record.status == 0){//失败
            //   return (
            //     <a
            //       onClick={() => {
            //         this.handleDownloadLog(record)
            //       }}
            //     >
            //       重新执行
            //     </a>
            //   );

            // }else{
            //   return ''
            // }
           
          }
        }
      }
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination?.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      // rowKey: (record: any) => record.id,
      dataSource: list,
      loading,
      pagination: paginationProps,
      // rowSelection,
      // selectedRowKeys,
      scroll: { x: 'max-content' }
    }




    // const {} = this.state
    return (
      <Modal
        title="任务中心"
        // style={{ width: '800px' }}
        width={900}
        bodyStyle={{ maxHeight: '700px' }}
        footer={null}
        visible={modalVisible}
        onCancel={this.close}
      >
        <PateoSearchForm
          onRef={(val: any) => this.searchForm = val}
          searchItems={searchItems}
          fetchParams={{ type: 'dataCollectionTaskCenter/getFetchPage', url: '/remote/config/taskCenter/page' }}
          extraArgs={{ page: 1, size:10, functionType: 'collectionConfig', }}
          saveFormValues={(val:any) =>
            this.setState({
              formValues: Object.assign(formValues, val),
            })
          }
          handleFormReset={this.handleFormReset}
          // handleFieldsValue={this.dataFormat}
        />

        <div className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{type: 'dataCollectionTaskCenter/getFetchPage', url: '/remote/config/taskCenter/page', extraArgs: {functionType: 'collectionConfig'} }}
            formValues={formValues}
            currentName="page"
            pageSizeName="size"
          />
        </div>
      </Modal>
    )
  }
}

export default connect(mapStateToProps)(TaskCenter);
